package cn.com.libertymutual.sys.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.repository.CrudRepository;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sys.bean.SysRole;
import cn.com.libertymutual.sys.bean.SysRoleMenu;
import cn.com.libertymutual.sys.dao.ISysRoleDao;
import cn.com.libertymutual.sys.dao.ISysRoleMenuDao;
import cn.com.libertymutual.sys.service.api.RoleUserService;

import com.alibaba.fastjson.JSONArray;
/**
 * @author:dylan.qiu
 * @date:   2017年8月11日 下午1:36:54
 */
@Service("RoleUserService")
public class RoleUserServiceImpl implements RoleUserService {
	private Logger log = LoggerFactory.getLogger(getClass());
	
	/*@Autowired
	@Qualifier("mysqlJdbcTemplate")
	protected JdbcTemplate mysqlJdbcTemplate;*/

	@Autowired
	private ISysRoleDao sysRoleDao;
	
	@Autowired
	private ISysRoleMenuDao sysRoleMenuDao;
	
	@Override
	public JSONArray getNotExistMenu(String roleId) {
		String sql = "select m.MENUID,m.MENUNAME  from tb_sys_menu m where  not exists (select  rm.MENUID  from tb_sys_role_menu rm where  rm.ROLEID="+roleId+" and rm.MENUID = m.MENUID )";
		return null;
		//return JSONArray.parseArray(mysqlJdbcTemplate.queryForList(sql).toString().replaceAll("=", ":").replaceAll(":", ":'").replaceAll(",", "',").replaceAll("}", "'}").replaceAll("}',", "},"));
	}
	
	@Override
	public ServiceResult roleFindAll(boolean isLookup, String lookupDataOne,
			String lookupDataTwo, int pageNumber, int pageSize,
			String sortfield, String sorttype) {
		ServiceResult sr=new ServiceResult();
		Sort sort=null;
		if("ASC".equals(sorttype) ){
			sort =new Sort(Direction.ASC,sortfield);
		}else{
			sort =new Sort(Direction.DESC,sortfield);
		}
	
		
		if(isLookup){
			//设置查询条件 
			sr.setResult(sysRoleDao.findAll(new Specification<SysRole>(){  
				@Override
				public Predicate toPredicate(Root<SysRole> root,
						CriteriaQuery<?> query, CriteriaBuilder cb) {			     			        
					List<Predicate> list = new ArrayList<>();
					list.add(cb.like(root.get("rolename").as(String.class),"%"+lookupDataOne+"%"));
					list.add(cb.like(root.get("remarks").as(String.class),"%"+lookupDataTwo+"%"));
					Predicate[] p = new Predicate[list.size()];
					
					
					return cb.and(list.toArray(p));
				}  
	        }, PageRequest.of(pageNumber - 1, pageSize, sort)));
		}else{
			sr.setResult(sysRoleDao.findAll(PageRequest.of(pageNumber - 1, pageSize, sort)));
		}
		return sr;
	}
	@Override
	public JSONArray roleManuFind(String roleId) {
		String sql = "select  m.MENUID as MENUID,m.MENUNAME as MENUNAMENAME  from tb_sys_role_menu rm,tb_sys_menu m  where rm.MENUID = m.MENUID and rm.ROLEID = " + roleId;
		//Object result = mysqlJdbcTemplate.queryForList(sql);
		JSONArray jr =null;// JSONArray.parseArray(result.toString().replaceAll("=", ":").replaceAll(":", ":'").replaceAll(",", "',").replaceAll("}", "'}").replaceAll("}',", "},"));
		return jr;
	}
	@Override
	public ServiceResult saveRoleMenu(SysRoleMenu sysRoleMenu) {
		return baseJpaOperation(sysRoleMenuDao,sysRoleMenu,true);
	}
	@Override
	public ServiceResult deleteRoleMenu(SysRoleMenu sysRoleMenu) {
		return baseJpaOperation(sysRoleMenuDao,sysRoleMenu,false);
	}
	@Override
	public ServiceResult saveRole(SysRole sysRole) {
		return baseJpaOperation(sysRoleDao,sysRole,true);
	}
	@Override
	public ServiceResult deleteRole(SysRole sysRole) {
		return baseJpaOperation(sysRoleDao,sysRole,false);
	}
	
	public ServiceResult baseJpaOperation(CrudRepository jpa,Object obj,boolean operation){
		ServiceResult sr = new ServiceResult();
		try{
			if(operation){
				jpa.save(obj);
			}else{
				jpa.delete(obj);
			}
			sr.setSuccess();
		}catch(Exception e){
			log.info(e.getMessage() ,e);
			sr.setFail();
			sr.setResult("操作失败！");
		}
		return sr;		
	}
	
}
